<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select
          v-model="queryParams.category"
          placeholder="请选择类别"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="(item, index) in categoryList"
            :key="index"
            :label="item.dictLabel"
            :value="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="咨询时间" prop="advisoryTime">
        <el-date-picker
          clearable
          v-model="queryParams.advisoryTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择咨询时间"
          :picker-options="setDisabled"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workstation:medicationAdvisory:add']"
        >新增用药咨询
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="medicationAdvisoryList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column label="用户姓名" align="center" prop="userName"/>
      <el-table-column label="类别" align="center" prop="category">
        <template slot-scope="scope">
          <span>{{
              scope.row.category == 1
                ? "医生"
                : scope.row.category == 2
                ? "护士"
                : "患者"
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="咨询内容" align="center" prop="advisoryContent"/>
      <el-table-column
        label="咨询时间"
        align="center"
        prop="advisoryTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.advisoryTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接收人" align="center" prop="receiveManName"/>
      <el-table-column
        label="接收时间"
        align="center"
        prop="receiveTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否处理" align="center" prop="isDispose"/>
      <el-table-column label="处理内容" align="center" prop="disposeContent"/>
      <el-table-column
        label="处理时间"
        align="center"
        prop="disposeTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.disposeTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workstation:medicationAdvisory:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workstation:medicationAdvisory:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用药咨询对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别" prop="category">
          <!-- <el-input v-model="form.category" placeholder="请输入类别" /> -->
          <el-radio-group v-model="form.category">
            <el-radio
              v-for="(item, index) in categoryList"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictLabel }}
            </el-radio
            >
          </el-radio-group>
        </el-form-item>
        <!-- 等于3 说明选择了患者  需要联动查询 -->
        <el-form-item
          label="用户姓名"
          prop="userName"
          v-if="form.category == 3"
        >
          <el-autocomplete
            style="width: 100%;"
            v-model="form.userName"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入用户姓名"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName" v-else>
          <el-input v-model="form.userName" placeholder="请输入用户姓名"/>
        </el-form-item>
        <el-form-item label="咨询内容">
          <el-input
            type="textarea"
            :rows="4"
            v-model="form.advisoryContent"
            placeholder="请输入咨询内容"
          />
        </el-form-item>
        <el-form-item label="咨询时间" prop="advisoryTime">
          <el-date-picker
            clearable
            v-model="form.advisoryTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择咨询时间"
            :picker-options="setDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接收人" prop="receiveManName">
          <el-input
            :value="$store.state.user.user.nickName"
            placeholder="请输入接收人"
            disabled
          />
        </el-form-item>
        <el-form-item label="接收时间" prop="receiveTime">
          <el-date-picker
            clearable
            v-model="form.receiveTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择接收时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理内容">
          <el-input
            type="textarea"
            :rows="4"
            v-model="form.disposeContent"
            placeholder="请输入处理内容"
          />
        </el-form-item>
        <el-form-item label="处理时间" prop="disposeTime">
          <el-date-picker
            clearable
            v-model="form.disposeTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择处理时间"
            :picker-options="setDisabled"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
        >确 定
        </el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMedicationAdvisory,
  getMedicationAdvisory,
  delMedicationAdvisory,
  addMedicationAdvisory,
  updateMedicationAdvisory,
} from "@/api/workstation/medicationAdvisory/medicationAdvisory.js";
import {listBaseInfo} from "@/api/workstation/baseInfo";

export default {
  name: "MedicationAdvisory",
  data() {
    return {
      setDisabled: {
        // 返回禁用时间
        disabledDate(time) {
          return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
        },
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用药咨询表格数据
      medicationAdvisoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        category: undefined,
        advisoryContent: undefined,
        advisoryTime: undefined,
        receiveManId: undefined,
        receiveManName: undefined,
        receiveTime: undefined,
        isDispose: undefined,
        disposeContent: undefined,
        disposeTime: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: true, message: "用药咨询ID不能为空", trigger: "blur"},
        ],
        userName: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"},
        ],
        category: [
          {required: true, message: "类别不能为空", trigger: "blur"},
        ],
        advisoryContent: [
          {required: true, message: "咨询内容不能为空", trigger: "blur"},
        ],
        advisoryTime: [
          {required: true, message: "咨询时间不能为空", trigger: "blur"},
        ],
        receiveManId: [
          {required: true, message: "接收人ID不能为空", trigger: "blur"},
        ],
        receiveTime: [
          {required: true, message: "接收时间不能为空", trigger: "blur"},
        ],
        isDispose: [
          {required: true, message: "是否处理不能为空", trigger: "blur"},
        ],
        disposeContent: [
          {required: true, message: "处理内容不能为空", trigger: "blur"},
        ],
        disposeTime: [
          {required: true, message: "处理时间不能为空", trigger: "blur"},
        ],
      },
      dicts: ["advisory_category"],
      categoryList: [], // 字典类别数组
    };
  },
  created() {
    this.getList();
    // 字典查询类别
    this.getDicts(this.dicts[0]).then((res) => {
      this.categoryList = res.data;
    });
  },
  computed: {
    userId() {
      return this.$store.state.user.user.userId;
    },
  },
  methods: {
    querySearchAsync(queryString, cb) {
      let results = [];
      if (queryString == "") {
        cb(results);
      } else {
        //掉接口需要的参数
        let queryParams = {
          pageNum: 1,
          pageSize: 9999,
          patientName: queryString,
        };
        //这里去查询后端的接口.根据自己接口的情况进行赋值
        listBaseInfo(queryParams).then((res) => {
          if (res.code == 200) {
            let resArr = res.rows;
            //循环放到一个远程搜索需要的数组
            resArr.forEach((item) => {
              results.push({
                value: item.medicalRecordNo + '-' + item.patientName,
                id: item.medicalRecordNo,
                name: item.patientName
              });
            });
            cb(results);
          } else {
            results = [];
            cb(results);
          }
        });
      }
    },
    //点击出现搜索后点击的每一项
    handleSelect(item) {
      this.form.userName = item.name;
      this.form.medicalRecordNo = item.id;
    },
    /** 查询用药咨询列表 */
    getList() {
      this.loading = true;
      listMedicationAdvisory(this.queryParams).then((response) => {
        this.medicationAdvisoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userName: undefined,
        category: undefined,
        advisoryContent: undefined,
        advisoryTime: undefined,
        receiveManId: undefined,
        receiveManName: undefined,
        receiveTime: undefined,
        isDispose: undefined,
        disposeContent: undefined,
        disposeTime: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用药咨询";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getMedicationAdvisory(id).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改用药咨询";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMedicationAdvisory(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            this.form.receiveManId = this.userId;
            addMedicationAdvisory(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(`是否确认删除 ${row.userName} 的用药咨询数据项？`)
        .then(() => {
          this.loading = true;
          return delMedicationAdvisory(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workstation/medicationAdvisory/export",
        {
          ...this.queryParams,
        },
        `medicationAdvisory_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
